package org.skycloud.mybatis.utils;

import static java.util.regex.Pattern.compile;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

public final class DatabaseIdUtils {

	private DatabaseIdUtils() {
	}

	private static final Map<Pattern, String> PRODUCT_NAME_TO_DATABASE_ID_LOOKUP = new HashMap<Pattern, String>();

	static {
		PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.put(compile("(?i)oracle.*"), "oracle");
		PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.put(compile("(?i).*db2.*"), "db2");
		PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.put(compile("(?i)mysql.*"), "mysql");
		PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.put(compile("(?i)postgresql.*"), "postgresql");
		PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.put(compile("(?i)sqlite.*"), "sqlite");
	}

	public static String getDatabaseId(String databaseProductName) {
		if (databaseProductName == null) {
			return null;
		}

		for (Entry<Pattern, String> entry : PRODUCT_NAME_TO_DATABASE_ID_LOOKUP.entrySet()) {
			if (entry.getKey().matcher(databaseProductName).matches()) {
				return entry.getValue();
			}
		}

		return null;
	}
}
